package com.elmcode.server.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.elmcode.server.config.RabbitMQConfig;
import com.elmcode.server.elmenum.OrderStatusEnum;
import com.elmcode.server.elmenum.PayStatusEnum;
import com.elmcode.server.entity.AddressEntity;
import com.elmcode.server.entity.BookDetailEntity;
import com.elmcode.server.entity.BookEntity;
import com.elmcode.server.exception.BusException;
import com.elmcode.server.interceptor.LoginInterceptor;
import com.elmcode.server.service.*;
import com.elmcode.server.vo.CartItemVo;
import com.elmcode.server.vo.CartVo;
import com.elmcode.server.vo.CustomerVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    AddressService addressService;

    @Autowired
    CartService cartService;

    @Autowired
    BookDetailService bookDetailService;

    @Autowired
    BookService bookService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Transactional
    @Override
    public Map<String,Object> createOrder(Long addressId, String remark) {
        BookEntity order = new BookEntity();
        //TODO 1、设置订单号
        String orderId = IdWorker.getTimeId();
        order.setNum(orderId);

        //TODO 2、获取顾客的信息
        CustomerVo customer = LoginInterceptor.threadLocal.get();
        order.setCustomerId(customer.getId());
        order.setCustomerName(customer.getName());


        //TODO 3、设置订单列表  t_book_detail
        CartVo cart = cartService.getCart();
        List<CartItemVo> cartItemVos = cart.getCartItemVos();

        if(cartItemVos != null){
            List<BookDetailEntity> collect = cartItemVos.stream().map(item -> {
                BookDetailEntity detailEntity = new BookDetailEntity();

                BeanUtils.copyProperties(item, detailEntity);
                detailEntity.setBookId(orderId);

                String foodFlavor = item.getFlavorItem() + ":" + item.getFlavorValue();
                detailEntity.setFoodFlavor(foodFlavor);

                detailEntity.setTotal(item.getCount());
                detailEntity.setAmount(item.getPrice().multiply(new BigDecimal(item.getCount())));

                return detailEntity;
            }).collect(Collectors.toList());
            bookDetailService.saveBatch(collect);
        }

        //TODO 4、设置基本信息  状态  备注
        order.setAmount(cart.getTotalPrice());
        order.setCreateTime(new Date());
        order.setStatus(OrderStatusEnum.PENDING_PAYMENT.getCode());
        order.setRemark(remark);

        //TODO 5、获取地址信息
        AddressEntity address = addressService.getById(addressId);
        BeanUtils.copyProperties(address,order);

        order.setPhone(address.getPhone());
        order.setAddressId(addressId);
        order.setAddress(address.getDetail());
        //设置收货人
        order.setConsignee(address.getConsignee());

        //TODO 6、保存订单
        bookService.save(order);

        //TODO 7、清空购物车
        cartService.clearCart();


        //TODO 8、将订单order发送给消息队列
        try {
            rabbitTemplate.convertAndSend(RabbitMQConfig.ORDER_EVENT_EXCHANGE,RabbitMQConfig.EXCHANGE_TO_DELAY_QUEUE_KEY,order);
        }catch (Exception e){
        }

        Map<String,Object> map = new HashMap<>();
        map.put("num",order.getNum());
        map.put("amount",order.getAmount().toString());

        return map;
    }

    @Override
    public void closeOrder(BookEntity order) {
        //从数据库中查出最新的订单信息
        BookEntity orderByNum = bookService.getOrderByNum(order.getNum());

        //判断当前订单是否 为 待支付状态 并且 为未支付状态
        if(orderByNum.getStatus().equals(OrderStatusEnum.PENDING_PAYMENT.getCode())
                && orderByNum.getPayStatus().equals(PayStatusEnum.PAY_STATUS_NO.getCode())){
            orderByNum.setCancelTime(new Date());
            orderByNum.setStatus(OrderStatusEnum.CANCELLED.getCode());

            orderByNum.setPayStatus(PayStatusEnum.PAY_STATUS_NO.getCode());
            orderByNum.setCancelReason("订单长时间未支付，系统自动取消");

            bookService.updateByNum(orderByNum);

            //TODO 把订单详情表的对应字段删除
//            bookDetailService.delectByBookId(order.getNum());

        }else {
            throw new BusException("订单已被支付");
        }
    }
}
